<template>
  <div class="page-container">
    <div class="page-row">
        <el-card shadow="hover" style="flex:auto;margin-right:10px;margin-top:10px" :body-style="{padding: `11px`}">
            <el-row align="middle">
                <div style="margin-right:10px">
                    <div class="tips-data">
                        <span class="tips">订单阶段</span>
                        <el-icon @click="openLifeSetting" size="13px" style="cursor: pointer;"><ele-Setting style="color:#909399;" /></el-icon>
                    </div>
                    <div class="tips-data">
                        <span class="tips small-tips">当前数据</span>
                    </div>
                    <div class="tips-data">
                        <span class="tips small-tips">今日新增</span>
                    </div>
                    <div class="tips-data">
                        <span class="tips small-tips">昨日新增</span>
                    </div>
                </div>
                <el-row style="flex:1;">
                    <div class="tips-cell" v-for="(item, index) in orderStatus" :key="item.id">
                        <div class="tips-item">
                            <span :class="['tips-name', item.id < 0 ? 'red' : '']">{{item.name}}</span>
                            <el-icon v-if="index < orderStatus.length - 1"><ele-DArrowRight /></el-icon>
                        </div>
                        <!-- 当前数据 -->
                        <p :class="['item-data', index < orderStatus.length - 1 ? 'item-right' : '']">{{dataAll[item.label] || 0}}</p>
                        <!-- 今日新增 -->
                        <p :class="['item-data', dataDay[item.label] < 0 ? 'green' : (dataDay[item.label] == 0 || !dataDay[item.label])? '' : 'red', index < orderStatus.length - 1 ? 'item-right' : '']">
                            <template v-if="dataDay[item.label] > 0">+</template>{{dataDay[item.label] || 0}}
                        </p>
                        <!-- 昨日新增 -->
                        <p :class="['item-data', dataLast[item.label] < 0 ? 'green' : (dataLast[item.label] == 0 || !dataLast[item.label])? '' : 'red', index < orderStatus.length - 1 ? 'item-right' : '']">
                            <template v-if="dataLast[item.label] > 0">+</template>{{dataLast[item.label] || 0}}
                        </p>
                    </div>
                </el-row>
            </el-row>
        </el-card>
        <el-card shadow="hover" style="margin-top:10px;width:35%;min-width:555px;" :body-style="{padding: `11px 0`, height: `100%`}">
            <el-row style="height: 100%">
                <el-col :span="6">
                    <div class="col-cell before">
                        <p class="col-tips">昨日新增</p>
                        <p class="col-data">{{accountData.lastDay || 0}}</p>
                    </div>
                </el-col>
                <el-col :span="6">
                    <div class="col-cell current">
                        <p class="col-tips">今日新增</p>
                        <p class="col-data">{{accountData.nowDay || 0}}</p>
                    </div>
                </el-col>
                <el-col :span="6">
                    <div class="col-cell current">
                        <p class="col-tips">本月订单总数</p>
                        <p class="col-data">{{accountData.monthDay || 0}}</p>
                    </div>
                </el-col>
                <el-col :span="6">
                    <div class="col-cell current">
                        <p class="col-tips">本月退款订单数</p>
                        <p class="col-data">{{accountData.returnOrder || 0}}</p>
                    </div>
                </el-col>
                <el-col :span="6">
                    <div class="col-cell before">
                        <p class="col-tips">昨日新增金额</p>
                        <p class="col-data">{{accountData.lastMoney || 0}}</p>
                    </div>
                </el-col>
                <el-col :span="6">
                    <div class="col-cell current">
                        <p class="col-tips">今日新增金额</p>
                        <p class="col-data">{{accountData.nowMoney || 0}}</p>
                    </div>
                </el-col>
                <el-col :span="6">
                    <div class="col-cell current">
                        <p class="col-tips">本月订单总金额</p>
                        <p class="col-data">{{accountData.monthMoney || 0}}</p>
                    </div>
                </el-col>
                <el-col :span="6">
                    <div class="col-cell current">
                        <p class="col-tips">本月退款金额</p>
                        <p class="col-data">{{accountData.returnMoney || 0}}</p>
                    </div>
                </el-col>
            </el-row>
        </el-card>
    </div>
    <el-row style="margin: 10px 0" justify="space-between">
        <el-row>
            <el-button size="small" type="primary" @click="createOrder">新建生效订单</el-button>
            <el-button size="small" type="warning" @click="handleVerify">订单核销</el-button>
            <el-button size="small" type="danger" @click="adjustOrder">订单调整</el-button>
            <el-button size="small" type="default" plain @click="checkAll">全部订单</el-button>
            <el-row>
                <el-date-picker
                    v-model="search.range"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    size="small"
                    style="margin-left:10px;"
                    value-format="YYYY-MM-DD"
                    @change="bindSearch"
                />
            </el-row>
        </el-row>
        <el-row>
            <el-button size="small" type="warning" plain @click="openDraft">草稿箱</el-button>
            <el-button type="default" size="small" @click="setHeader">表头设置</el-button>
        </el-row>
    </el-row>
    <div class="table-box">
        <el-table :data="list" size="small" class="tableList" :summary-method="getSummaries" show-summary :row-class-name="tableRowClassName" :row-style="rowColorState">
            <el-table-column type="selection" width="30" fixed="left"></el-table-column>
            <el-table-column v-for="item in header" :key="item.id" :prop="item.label" :min-width="item.name.length > 5 ? `130px` : `90px`" :align="item.label !== 'productName' ? 'center' : 'left'" :width="item.label !== 'productName' ? `unset` : '400px'" :class-name="item.label !== 'productName' ? '' : 'order-goods'">
                <template #header>
                    <span v-if="item.label !== 'productName'" style="margin-right:2px;">{{item.name}}</span>
                    <el-row class="order-row-item order-border-none" v-else>
                        <el-col :span="6">产品名称</el-col>
                        <el-col :span="6">详情/规格</el-col>
                        <el-col :span="4">数量</el-col>
                        <el-col :span="4">单价(元)</el-col>
                        <el-col :span="4">折扣</el-col>
                    </el-row>
                    <!-- 可搜索表头 -->
                    <el-popover
                        placement="bottom"
                        :width="100"
                        trigger="click"
                        v-if="item.isFilter && item.filter == 'search'">
                        <template #reference>
                            <el-icon :size="15" color="var(--el-color-primary)"><ele-Search /></el-icon>
                        </template>
                        <el-input 
                            :placeholder="`请输入${item.name}`"
                            v-model.trim="search[item.label]"
                            size="small"
                            title="按下回车即可搜索"
                            clearable
                            @keydown.enter="bindSearch">
                        </el-input>
                    </el-popover>
                    <!-- 可筛选表头 -->
                    <el-popover
                        placement="bottom"
                        :width="60"
                        trigger="click"
                        @after-leave="bindSearch"
                        v-if="item.isFilter && item.filter == 'filter'">
                        <template #reference>
                            <el-icon :size="15" color="var(--el-color-primary)"><ele-Filter /></el-icon>
                        </template>
                        <el-scrollbar max-height="600px">
                            <el-radio-group v-model="search[item.label]" size="small" v-if="filterList[item.label].length > 0">
                                <el-radio  v-for="radio in filterList[item.label]" :key="radio.name" :label="radio.id" @click.prevent="onRadioChange(radio.id, item.label)">{{radio.name}}</el-radio>
                            </el-radio-group>
                            <el-empty style="padding: 0;font-size:12px;" v-else :image-size="50" description="无数据" />
                        </el-scrollbar>
                    </el-popover>
                </template>
                <template #default="scope">
                    <template v-if="item.label == 'productName'">
                        <div style="flex:1;display:flex;flex-direction: column;">
                            <div v-for="(order, index) in scope.row.orderItemList" :key="order.id" style="flex: 1;height:100%">
                                <el-row class="order-row-item" style="height:100%">
                                    <el-col :span="6">{{order.spuName}}</el-col>
                                    <el-col :span="6">{{order.skuName}}</el-col>
                                    <el-col :span="4">{{order.skuQuantity}}</el-col>
                                    <el-col :span="4">{{order.skuPrice}}</el-col>
                                    <el-col :span="4">折扣</el-col>
                                </el-row>
                                <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)" v-if="index < scope.row.orderItemList.length - 1" />
                            </div>
                        </div>
                    </template>
                    <template v-else-if="item.label == 'sourceType'">
                        <span v-if="scope.row.customerSourceId">{{ scope.row.customerSource }}</span>
                        <span v-else>{{ getStatusText(item.label, scope.row[item.label]) }}</span>
                    </template>
                    <template v-else-if="item.isFilter && item.filter == 'filter'">
                        {{getStatusText(item.label, scope.row[item.label])}}
                    </template>
                    <template v-else-if="item.label == 'settlement'">
                        {{ settlementList[scope.row.settlement]}}
                    </template>
                    <template v-else-if="item.label == 'paymentTime'">
                        {{ scope.row.paymentTime == null?'待付款':'已付款' }}
                    </template>
                    <template v-else-if="item.label == 'saleMoney'">
                        {{ scope.row.placeType == 0?0:sumSkuSaleMoney(scope.row.orderItemList) }}
                    </template>
                    <template v-else-if="item.label == 'placeType'">
                        {{ scope.row.placeType == 0?'自营':'17购' }}
                    </template>
                    <template v-else-if="item.label == 'payAmount'">
                        {{ scope.row.payAmount - scope.row.reduceMoney }}
                    </template>
                    <template v-else-if="item.label == 'classOther'">
                        {{ scope.row.classOther == 0 ? '个人':'企业' }}
                    </template>
                    <template v-else-if="item.label == 'customerName'">
                            <span class="primary" @click="openDetail(scope.row)">{{ scope.row.customerName }}</span>
                        </template>
                    <template v-else-if="item.label == 'orderType'">
                        <span v-if="scope.row.rootIn == 6">调整单</span>
                        <span v-else>{{ getStatusText('sourceType', scope.row['sourceType']) }}</span>
                    </template>
                    <template v-else>{{scope.row[item.label]}}</template>
                </template>
            </el-table-column>
            <el-table-column fixed="right" width="180px" label="操作">
                <template #default="scope" >
                    <!-- <el-button size="small" link type="primary" @click="approval(scope.row)">审批</el-button> -->
                    <el-button size="small" link type="primary" @click="logistic(scope.row)" v-if="(scope.row.status == 1 || scope.row.status == 2 || scope.row.sourceType == 2 || scope.row.sourceType == 3) && scope.row.sourceType != 4">去发货</el-button>
                    <el-button size="small" link type="primary" @click="afterSale(scope.row)" v-if="scope.row.status == 3">售后</el-button>
                    <el-button size="small" link type="primary" @click="editOrder(scope.row)" v-if="scope.row.status == 0">编辑</el-button>
                    <el-button size="small" link type="primary" @click="checkDetail(scope.row)">查看详情</el-button>
                    <el-button size="small" link type="primary" @click="getFund(scope.row)" v-if="scope.row.paymentTime == null && (scope.row.sourceType == 2 || scope.row.sourceType == 3)">回款</el-button>
                    <el-button size="small" link type="primary" @click="signOrder(scope.row)" v-if="scope.row.status == 2">确认签收</el-button>
                    <el-button size="small" link type="primary" @click="editPayMoney(scope.row)" v-if="scope.row.isApprove == 0 && scope.row.paymentTime == null && (scope.row.status != 4 && scope.row.status != 5) && scope.row.isEditPay == 1">改价</el-button>
                    <el-button size="small" link type="primary" @click="showReceipt(scope.row)" v-if="scope.row.receiptList.length > 0" >查看回执</el-button>
                    <el-button size="small" link type="primary" @click="uploadContract(scope.row)" v-if="scope.row.contractFileUrl">下载电子合同</el-button>
                    <el-button size="small" link type="danger" @click="sortSink(scope.row)" v-if="scope.row.sort != 99">订单完结</el-button>
                    <!-- <el-button size="small" link type="danger" @click="eraseAmount(scope.row)" v-if="scope.row.isErase == 0 && scope.row.receiveMoney > 0 && scope.row.receiveMoney < scope.row.payAmount && scope.row.paymentTime == null">抹零</el-button> -->
                    <el-button size="small" link type="danger" @click="cancelOrder(scope.row)" v-if="scope.row.status == 0 && scope.row.paymentTime == null">订单取消</el-button>

                </template>
            </el-table-column>
            <el-table-column fixed="right" align="center" width="80" label="发送方式">
                <template #default="scope">
                    <el-button size="small" link type="primary" v-if="scope.row.sourceType == 3 && scope.row.purchaseOrderId == null" @click="directSend(scope.row)">直发</el-button>
                    <el-button link type="primary" v-else @click="showWeChatShare(scope.row)">
                        <i class="fa fa-weixin" aria-hidden="true"></i>
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="page-block">
        <el-pagination
            v-model:currentPage="current"
            v-model:page-size="page"
            :page-sizes="[10, 20, 30, 40]"
            :small="true"
            :disabled="false"
            :background="false"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    <order-detail v-model:dialogDrawer="dialogDetail" v-model:defaultForm="rowForm" @onDelete="detailDel"></order-detail>
    <logistic-detail v-model:dialogDrawer="dialogLogistic" v-model:defaultForm="rowForm" @onSubmit="logisticSubmit"></logistic-detail>
    <create-order v-model:dialogDrawer="dialogCreate" :title="title" v-model:defaultForm="rowForm" v-model:isEdit="isEdit" v-model:entrance="entrance" @onSubmit="refreshList"></create-order>
    <header-setting v-model:dialogDrawer="dialogHeader" v-model:defaultHeader="header" @onSubmit="headerSubmit"></header-setting>
    <fund-detail v-if="dialogFund" v-model:dialogDrawer="dialogFund" :defaultForm="rowForm" @onSubmit="refreshList"></fund-detail>
    <cancel-order v-model:dialogDrawer="dialogCancel" v-model:defaultForm="rowForm" @onSubmit="cancelSubmit"></cancel-order>
    <after-sale-detail v-if="dialogAfterSale" v-model:dialogDrawer="dialogAfterSale" v-model:defaultForm="rowForm"></after-sale-detail>
    <draft-list v-model:dialogDrawer="dialogDraft"></draft-list>
    <verification v-model:dialogDrawer="dialogVerify" :userList="userList" @onSubmit="submitVerification"></verification>
    <edit-order-money v-model:dialogDrawer="dialogEditMoney" v-model:defaultForm="rowForm" v-model:maxMoney="maxMoney" @onSubmit="refreshList"></edit-order-money>
    <!-- 客户详情 -->
    <customer-detail v-model:dialogDrawer="customerDialog" :detail-data="detailData"/>
    <!-- 回执单 -->
    <receipt-detail v-model:dialogDrawer="receiptDialog" :detailData="receiptData"/>
  </div>
</template>

<script>
import { reactive, toRefs, onMounted, computed, h } from 'vue'
import OrderDetail from '../components/OrderDetail.vue'
import LogisticDetail from '../components/LogisticDetail.vue'
import CreateOrder from '../components/CreateOrder.vue'
import HeaderSetting from '../components/HeaderSetting.vue'
import FundDetail from '../components/FundDetail.vue'
import CancelOrder from '../components/CancelOrder.vue'
import AfterSaleDetail from '../components/AfterSaleDetail.vue'
import DraftList from '../components/DraftList.vue'
import Verification from '../components/Verification.vue'
import EditOrderMoney from '../components/EditOrderMoney.vue'
import CustomerDetail from '/@/views/crm/components/CustomerDetail.vue'
import ReceiptDetail from '../components/ReceiptDetail.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import { useOrderApi } from '/@/api/order/index'
import { storeToRefs } from 'pinia';
import { orderModelStatus } from '/@/stores/order'
import Cookies from 'js-cookie'
import opportunityApi from '/@/api/ums/customer/opportunity'
import api from '/@/api/commonApi'
export default {
    name: 'OrderIndex',
    components: { 
        OrderDetail, 
        LogisticDetail, 
        CreateOrder, 
        HeaderSetting, 
        FundDetail,
        CancelOrder,
        AfterSaleDetail,
        DraftList,
        Verification,
        EditOrderMoney,
        CustomerDetail,
        ReceiptDetail
    },
    setup() {
        const orderApi = useOrderApi()
        const storeOrder = orderModelStatus() // 订单各类状态数据
        const state = reactive({
            // orderStatus: [{
            //     name: '待审批',
            //     id: 1,
            //     label: 'stayApprove'
            // },{
            //     name: '已审批',
            //     id: 2,
            //     label: 'yetApprove'
            // },{
            //     name: '待付款',
            //     id: 3,
            //     label: 'awaitPay'
            // },{
            //     name: '待发货',
            //     id: 4,
            //     label: 'awaitDeliver'
            // },{
            //     name: '待收货',
            //     id: 5,
            //     label: 'deliverGoods'
            // },{
            //     name: '重发补发',
            //     id: 6,
            //     label: 'anewDeliver'
            // },{
            //     name: '执行完毕',
            //     id: 7,
            //     label: 'accessStatus'
            // },{
            //     name: '待退款',
            //     id: 8,
            //     label: 'returnMoney'
            // },{
            //     name: '退款完毕',
            //     id: 9,
            //     label: 'returnMoneyAss'
            // },
            //  {
            //     name: '订单取消',
            //     id: -1,
            //     label: 'cancelStatus'
            // }],
            // 订单阶段
            orderStatus: [
                {
                    name: '待付款',
                    id: 3,
                    label: 'awaitPay'
                },
                {
                    name: '待发货',
                    id: 4,
                    label: 'awaitDeliver'
                },
                {
                    name: '待收货',
                    id: 5,
                    label: 'deliverGoods'
                },
                {
                    name: '已完成',
                    id: 7,
                    label: 'accessStatus'
                },
                {
                    name: '售后',
                    id: 10,
                    label: 'afterSale'
                }
            ],
            // 表头数据
            header: [{
                name: '订单号/合同编号',
                isFilter: true,
                filter: 'search',
                label: 'orderSn'
            },            
            {
                name: '客户名称',
                isFilter: true,
                filter: 'search',
                label: 'customerName'
            },
            {
                name: '平台',
                isFilter: false,
                filter: 'filter',
                label: 'placeType'
            },
            {
                name: '订单类别',
                isFilter: true,
                filter: 'filter',
                label: 'classOther'
            },
            {
                name: '产品名称',
                isFilter: false,
                filter: 'search',
                label: 'productName'
            }
            ,{
                name: '总价(元)',
                isFilter: false,
                filter: 'search',
                label: 'totalAmount'
            }
            ,{
                name: '折后价',
                isFilter: false,
                filter: 'search',
                label: 'discountAmount'
            }
            ,{
                name: '订单总金额',
                isFilter: false,
                filter: 'filter',
                label: 'totalAmount'
            }
            ,{
                name: '分销金',
                isFilter: false,
                filter: 'filter',
                label: 'saleMoney'
            }
            ,{
                name: '应收金额',
                isFilter: false,
                filter: 'filter',
                label: 'payAmount'
            }
            ,{
                name: '已收金额',
                isFilter: false,
                filter: 'filter',
                label: 'receiveMoney'
            }
            ,{
                name: '支付状态',
                isFilter: false,
                filter: 'filter',
                label: 'paymentTime'
            }
            ,{
                name: '订单阶段',
                isFilter: true,
                filter: 'filter',
                label: 'status'
            },
            // {
            //     name: '结款方式',
            //     isFilter: false,
            //     filter: 'filter',
            //     label: 'settlement'
            // }
            // ,{
            //     name: '发货状态',
            //     isFilter: true,
            //     filter: 'filter',
            //     label: 'deliveryStatus'
            // },{
            //     name: '要求交货日期',
            //     isFilter: false,
            //     filter: 'filter',
            //     label: 'requestDeliveryDate'
            // },{
            //     name: '发货方式',
            //     isFilter: true,
            //     filter: 'filter',
            //     label: 'deliveryType'
            // },
            {
                name: '下单日期',
                isFilter: false,
                filter: 'filter',
                label: 'createTime'
            }
            ,{
                name: '订单来源',
                isFilter: true,
                filter: 'filter',
                label: 'sourceType'
            },
            {
                name: '订单类型',
                isFilter: false,
                filter: 'filter',
                label: 'orderType'
            },
            ],
            settlementList: {
                0: "全款结付",
                1: "年付",
                2: "月付",
                3: "到货后付",
                4: "自定义",
                5: "预付充值",
            },
            search: {
                tableType: 2, // 表单类型：1 -> 审批和签署单，2 -> 生效订单，3 -> 代付款电商单
                range: '',
                orderSn: '',
                status: '',
                memberName: '',
                billType: '',
                payStatus: '',
                payType: '',
                deliveryStatus: '',
                deliveryType: '',
                sourceType: '',
                selectType: '',
            },
            accountData: {},
            list: [],
            filterList: storeToRefs(storeOrder),
            dataAll: {},
            dataDay: {},
            dataLast: {},
            totalAmount: 0,
            payAmount: 0,
            title: '新建订单',
            entrance: 'ORDER', // 新建订单 
            current: 1, // 当前页
            page: 10, // 条数
            total: 0, // 总数
            rowForm: {}, // row表单
            isEdit: false, // 是否编辑
            dialogLogistic: false,
            dialogDetail: false, // 订单详情
            dialogCreate: false,
            dialogHeader: false,
            dialogFund: false, // 回款
            dialogCancel: false, // 取消订单
            dialogAfterSale: false, // 售后
            dialogDraft: false, // 草稿箱
            dialogVerify: false, // 核销
            dialogEditMoney: false, // 改价
            maxMoney: 0, // 最大修改金额
            userList: [], // 核销用户
            customerDialog: false, // 客户详情
            detailData: {}, // 客户信息
            receiptDialog: false, // 回执开关
            receiptData: {}, // 回执信息
        })
        // 获取订单状态
        const getStatusText = computed(() => {
            return (label, val) => {
                const result = state.filterList[label].find(item => {
                    return item.id == String(val)
                })
                return result ? result.name : ''
            }
        })
        // 修改订单阶段生命周期
        const openLifeSetting = () => {

        }
        // 新建订单
        const createOrder = () => {
            state.dialogCreate = true
            state.entrance = 'ORDER'
            state.title = '新建订单'
        }
        // 搜索
        const bindSearch = () => {
            state.current = 1
            getList()
        }
        // 审批
        const approval = row => {
            console.log(row)
        }
        // 条数修改
        const handleSizeChange = e => {
            state.page = e
            getList()
        }
        // 页码修改
        const handleCurrentChange = e => {
            state.current = e
            getList()
        }
        // 发货 未确定
        const logistic = row => {
            state.rowForm = row
            state.dialogLogistic = true
        }
        // 取消订单
        const cancelOrder = row => {
            state.rowForm = row
            state.dialogCancel = true
        }
        // 售后
        const afterSale = row => {
            state.rowForm = row
            state.dialogAfterSale = true
        }
        // 编辑
        const editOrder = row => {
            state.rowForm = row
            state.isEdit = true
            state.dialogDetail = true
            state.title = '编辑订单'
        }
        // 查看详情
        const checkDetail = row => {
            state.rowForm = row
            state.dialogDetail = true
            state.isEdit = false
        }
        // 回款
        const getFund = row => {
            state.rowForm = row
            state.dialogFund = true
        }
        // 详情删除操作
        const detailDel = () => {

        }
        // 发货提交
        const logisticSubmit = () => {
            refreshList()
        }
        // 获取订单
        const getList = () => {
            // 需要将同一个订单的商品合并行
            const search = JSON.parse(JSON.stringify(state.search))
            delete search.range
            for(let key in search) {
                if(!search[key] && search[key] != '0') {
                    delete search[key]
                }
            }
            api.orderList({
                pageNum: state.current,
                pageSize: state.page,
                startTime: state.search.range ? state.search.range[0] : '',
                endTime: state.search.range ? state.search.range[1] : '',
                selectSource: 1,
                ...search
            }).then(res => {
                state.total = res.data.list.total
                state.list = res.data.list.records
                state.totalAmount = res.data.orderAllMoney
            })
        }
        // 表头设置
        const setHeader = () => {
            state.dialogHeader = true
        }
        // 表头数据提交
        const headerSubmit = (e) => {
            console.log(e)
        }
        // 取消订单提交
        const cancelSubmit = () => {
            getList()
        }
        // 全部订单
        const checkAll = () => {
            state.search = {
                tableType: 2, // 表单类型：1 -> 审批和签署单，2 -> 生效订单，3 -> 代付款电商单
                range: '',
                orderSn: '',
                status: '',
                memberName: '',
                billType: '',
                payStatus: '',
                payType: '',
                deliveryStatus: '',
                deliveryType: '',
                sourceType: '',
                selectType: '',
            }
            state.current = 1
            getList()
        }
        // 切换单选框
        const onRadioChange = (val, type) => {
            if(state.search[type] == String(val)){
                state.search[type] = ''
                return
            }
            state.search[type] = val
        }
        // 获取统计数据
        const getHeaderStatistics = () => {
            orderApi.getStatistics().then(res => {
                state.accountData = {
                    lastDay: res.data.lastDay,
                    monthDay: res.data.monthDay,
                    nowDay: res.data.nowDay,
                    returnOrder: res.data.returnOrder,
                    lastMoney: res.data.lastMoney,
                    nowMoney: res.data.nowMoney,
                    monthMoney: res.data.monthMoney,
                    returnMoney: res.data.returnMoney,
                }
                state.dataAll = res.data.dataAll
                state.dataDay = res.data.dataDay
                state.dataLast = res.data.dataLast
            })
        }
        // 统计金额数据
        const getSummaries = (params) => {
            const { columns, data } = params
            const sums = []
            const sumsProperty = ['totalAmount', 'payAmount']
            columns.forEach((column, index) => {
                if (index === 0){
                    sums[index] = ''
                    return
                }
                if (column.property === 'orderSn') {
                    sums[index] = (() => {
                        return h('div', { style: {color: 'var(--el-color-primary)',fontWeight: 'bold'} }, [h('p', '∑ 本页'), h('p', '∑ 全部')])
                    })();
                    return
                }
                const values = data.map((item) => Number(item[column.property]))
                // 合计应收金额, 订单总金额
                if (sumsProperty.includes(column.property)) {
                    sums[index] = (() => {
                        return h('div', [
                            `￥${values.reduce((prev, curr) => {
                                const value = Number(curr)
                                if (!Number.isNaN(value)) {
                                    return prev + curr
                                } else {
                                    return prev
                                }
                            }, 0)}`, h('p', `￥${state.totalAmount}`)])
                    })()
                    
                } else {
                    sums[index] = ''
                }
            })
            return sums
        }
        // 确认收货
        const signOrder = row => {
            let productNames = '<table border="1">'
            for(let i = 0; i < row.orderItemList.length; i++){
                productNames = productNames + '<tr><td style="width: 200px;">' + row.orderItemList[i].skuName + '</td><td style="width: 40px;">' + row.orderItemList[i].skuQuantity + '</td></tr>'
            }
            productNames = productNames + '</table>'
            ElMessageBox.confirm(
                `是否确定已收到：<br>${productNames}`,
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    dangerouslyUseHTMLString: true,
                }
            ).then(() => {
                orderApi.signForOrder({
                    deliveryId: row.deliveryId || '',
                    orderId: row.id
                }).then(() => {
                    ElMessage.success('签收成功')
                    getList()
                    getHeaderStatistics()
                })
            })
        }
        // 草稿箱
        const openDraft = () => {
            state.dialogDraft = true
        }
        // 核销提交
        const submitVerification = () => {
            refreshList()
        }
        // 核销订单
        const handleVerify = () => {
            api.getCardUserList().then(res => {
                state.userList = res.data
            })
            state.dialogVerify = true
        }
        // 刷新列表
        const refreshList = () => {
            getHeaderStatistics()
            getList()
        }
        // 弹出改价窗
        const editPayMoney = row => {
            state.rowForm = row
            state.maxMoney = 0
            row.orderItemList.forEach(item => {
                state.maxMoney += item.skuPrice * item.skuQuantity
            })
            state.dialogEditMoney = true
        }
        // 直发
        const directSend = row => {
            ElMessageBox.confirm('确定发送该笔订单至：' + row.customerName + '？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                api.orderSendPurchase(row).then(res => {
                    ElMessage.success('直发成功！')
                })
            })
        }
        // 微信分享
        const showWeChatShare = row => {
            console.log(import.meta.env.VITE_API_URL);
            ElMessageBox.confirm('确定发送该笔订单？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const url =  import.meta.env.VITE_API_URL
                const input = document.createElement('input')
                // input.value = url + 'share/wechatOrder/' + row.id
                // 测试地址
                input.value = "http://192.168.3.111:8888/#/share/wechatOrder/" + row.id
                document.body.appendChild(input)
                input.select()

                // 执行复制操作
                document.execCommand('Copy')

                document.body.removeChild(input)
                ElMessage.success('复制链接成功！')
            })
        }
        // 失效订单状态
        function  tableRowClassName(obj) {
            if (obj.row.status == 4 || obj.row.status == 5) {
                return 'error-row'
            } else if (obj.row.status == 3) {
                return 'success-row'
            }
            return ''
        }
        // 已读消息样式
        const rowColorState = (data) => {
            if (data.row.rootIn == 6) {
                return {
                    color: '#F56C6C'
                }
            }
            if(data.row.readed == 0) {
                return {
                    color: '#303133'
                }
            }else {
                return {
                    color: '#909399'
                }
            }
        }
        // 查看客户详情
        const openDetail = (customer) => {
            opportunityApi.getPage({
                current: 1,
                size: 10,
                nickname: customer.customerName,  // 客户简称
            }).then(res => {
                if (res.data.records.length > 0) {
                    state.detailData = res.data.records[0]
                    state.customerDialog = true
                }else {
                    ElMessage.warning("未找到此客户信息！")
                }
            }).catch(e => {
                console.log(e)
            })
        }
        // 查看回执
        const showReceipt = (data) => {
            state.receiptData = data
            state.receiptDialog = true
        }
        // 订单完结
        const sortSink = (data) => {
            ElMessageBox.confirm(
                `此订单(${data.orderSn})完结后就不可重回到该阶段!!!`,
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    dangerouslyUseHTMLString: true,
                }
            ).then(() => {
                api.finishAndSink({orderId: data.id}).then(res => {
                    if (res.data) {
                        getList()
                        ElMessage.success('订单已调整为完结')
                    }
                })
            }).catch(err => {

            })
        }
        // 下载电子合同
        const uploadContract = (data) => {
            ElMessageBox.confirm(
                `是否要下载此订单(${data.orderSn})的电子合同？`,
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    dangerouslyUseHTMLString: true,
                }
            ).then(() => {
                let names = data.contractFileUrl.split(".")
                let fileName = '订单电子合同-' + data.orderSn + '.' + names[names.length - 1]
                api.uploadFile({
                    fileUrl: data.contractFileUrl,
                    oldName: fileName
                }).then(response => {
                    const blob = new Blob([response.data], { type: 'application/blob' })
                    const reader = new FileReader()
                    reader.readAsDataURL(blob)
                    reader.onload = e => {
                        const a = document.createElement('a')
                        a.download = decodeURIComponent(fileName)
                        if (typeof e.target.result === 'string') {
                            a.href = e.target.result
                        }
                        a.click()
                    }
                    ElMessage.success("下载成功")
                })
            }).catch(err => {

            })
        }
        // 订单调整
        const adjustOrder = () => {
            state.dialogCreate = true
            state.entrance = 'ADJUST'
            state.title = '订单调整'
        }
        // 抹零
        const eraseAmount = (data) => {
            ElMessageBox.confirm(
                `是否要抹零掉此订单(${data.orderSn})？`,
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    dangerouslyUseHTMLString: true,
                }
            ).then(() => {
                ElMessage.success("抹零成功")
            }).catch(err => {

            })
        }
        // 分销金额
        function sumSkuSaleMoney(skuList) {
            let money = 0
            if (skuList.length > 0) {
                skuList.forEach(item => {
                    money += item.saleMoney
                })
            }
            return money
        }

        onMounted(() => {
            getHeaderStatistics()
            getList()
        })
        return {
            ...toRefs(state),
            openLifeSetting,
            createOrder,
            bindSearch,
            approval,
            sortSink,
            openDetail,
            showReceipt,
            rowColorState,
            handleSizeChange,
            handleCurrentChange,
            logistic,
            cancelOrder,
            afterSale,
            editOrder,
            checkDetail,
            getFund,
            detailDel,
            logisticSubmit,
            setHeader,
            headerSubmit,
            cancelSubmit,
            checkAll,
            adjustOrder,
            eraseAmount,
            onRadioChange,
            getStatusText,
            getSummaries,
            signOrder,
            openDraft,
            refreshList,
            editPayMoney,
            directSend,
            sumSkuSaleMoney,
            uploadContract,
            showWeChatShare,
            tableRowClassName,
            submitVerification,
            handleVerify
        }
    }
}
</script>

<style scoped lang="scss">
.page-container{
    padding: 5px 15px 15px !important;
    .page-row{
        display: flex;
        flex-wrap: wrap;
        align-items: stretch;
        .tips-data{
            display: flex;
            align-items: center;
            height: 28px;
            margin-top: 20px;
            .tips{
                margin-right: 3px;
                font-size: 13px;
            }
            &:first-child{
                height: unset;
                margin-top: 0;
            }
        }
        .tips-cell{
            flex: auto;
            .tips-item{
                display: flex;
                align-items: center;
                padding-left: 10px;
                justify-content: space-between;
            }
            .tips-name{
                margin-right: 10px;
                flex: 1;
                overflow: hidden;
                text-align: center;
            }
            .item-data{
                text-align: center;
                height: 28px;
                margin-top: 20px;
                line-height: 28px;
                color: var(--el-menu-text-color);
                font-size: 13px;
            }
            .item-right{
                margin-right: 14px;
            }
            .red {
                color: var(--el-color-danger)
            }
            .green{
                color: var(--el-color-success);
            }
        }
        .col-cell{
            padding: 10px 20px 0;
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            height: 100%;
            flex-wrap: wrap;
            .col-tips, .col-data{
                text-align: center;
            }
            .col-data{
                flex: auto;
                line-height: 100%;
                display: flex;
                justify-content: center;
                flex-direction: column;
                font-size: 44px;
                padding-top: 10px;
            }
        }
        .before{
            color: var(--el-color-danger);
        }
        .current{
            color: #626aef;
        }
    }
    .table-box{
        background: #fff;
        margin-top: 10px;
        :deep(.el-table__header-wrapper .el-table__cell) {
            background: var(--el-color-primary-light-9);
            color: var(--next-bg-menuBar-light-1);
        }
        .tableList{
            border: 1px solid var(--el-table-border-color);
            border-bottom: none;
            :deep(thead .cell) {
                display: flex;
                align-items: center;
                justify-content: center;
            }
            :deep(thead th:last-child .cell){
                justify-content: center;
            }
            :deep(thead .el-icon) {
                margin-top: -2px;
                cursor: pointer;
            }
            .primary{
                cursor: pointer;
                color: var(--el-color-primary);
            }
            :deep(.el-button){
                margin-left: 0;
                margin-right: 12px;
            }
            :deep(.el-table__body td.el-table__cell) {
                border-right: 1px solid var(--el-border-color-light);
                padding: 0;
                &:last-child{
                    border-right: none;
                }
            }
            .order-row-item{
                width: 100%;
                :deep(.el-col){
                    border-right: 1px solid var(--el-border-color-light);
                    text-align: center;
                    display:flex;
                    align-items: center;
                    justify-content: center;
                    &:last-child{
                        border-right: none;
                    }
                    &:first-child,
                    &:nth-child(2){
                        text-align: left;
                        justify-content: flex-start;
                        padding-left: 8px;
                    }
                }
            }
            .order-border-none{
                :deep(.el-col){
                    border: none;
                }
            }
        }
    }
}

:deep(.el-empty__description){
    margin-top: 5px;
    font-size: 11px;
}
</style>
<style lang="scss">
.order-goods .cell {
    padding: 0;
}
.el-table__body .order-goods .cell{
    min-height: 70px;
    display: flex;
    align-items: stretch;
    padding: 0;
}

.error-row{
    background: #C0C4CC !important;
}
.warning-row {
    background: #E6A23C !important;
}
.success-row{
    // background-color: #67C23A !important;
}
</style>